package com.icode.core.shared.usertype;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * User: alexz
 * Date: 15-1-20
 * Time: 下午4:40
 */
public class AuthorityListUserType extends AbstractHibernateUserType {

    @Override
    public int[] sqlTypes() {
        return new int[]{Types.VARCHAR};
    }

    @Override
    public Class returnedClass() {
        return List.class;
    }

    @Override
    public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException {
        String value = (String) StandardBasicTypes.STRING.nullSafeGet(rs, names, session, owner);
        if (value == null) {
            return Collections.emptyList();
        }
        String[] values = value.split(DELIMITER);
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String s : values) {
            GrantedAuthority authority = new SimpleGrantedAuthority(s);
            authorities.add(authority);
        }
        return authorities;
    }

    @Override
    public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException {
        if (value == null) {
            StandardBasicTypes.STRING.nullSafeSet(st, null, index, session);
        } else {
            List<GrantedAuthority> values = (List<GrantedAuthority>) value;
            String valueString = "";
            for (GrantedAuthority authority : values) {
                valueString += authority.getAuthority() + DELIMITER;
            }
            valueString = valueString.substring(0, valueString.lastIndexOf(DELIMITER));
            StandardBasicTypes.STRING.nullSafeSet(st, valueString, index, session);
        }
    }
}
